package org.example.controller;

import cn.lingyangwl.framework.core.utils.FileDownloadUtils;
import cn.lingyangwl.framework.tool.core.file.FileUtils;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.server.HttpServerResponse;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 二维码
 * @author shenguangyang
 */
@RestController
public class QrcodeController {
    @Resource
    private WxMpService wxMpService;

    /**
     * 获取临时二维码
     */
    @GetMapping("/getTmpQrcode")
    public void getTmpQrcode(HttpServletResponse response) throws WxErrorException, IOException {
        // 获取二维码的ticket
        // 获取临时二维码的ticket，其中scene为场景值，expire_seconds为二维码超时时间
        Integer expireSeconds = 60;
        String scene = UUID.randomUUID().toString();
        WxMpQrCodeTicket ticket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(scene, expireSeconds);
        File file = wxMpService.getQrcodeService().qrCodePicture(ticket);

        response.setHeader("Location", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLUtil.encode(ticket.getTicket()));
        response.setStatus(HttpStatus.FOUND.value());
    }

    /**
     * 获取永久二维码
     */
    @GetMapping("/getQrcode")
    public void getQrcode(HttpServletResponse response) throws WxErrorException, IOException {
        // 获取永久二维码的ticket，其中scene为场景值
        String scene = UUID.randomUUID().toString();
        WxMpQrCodeTicket ticket = wxMpService.getQrcodeService().qrCodeCreateLastTicket(scene);

        File file = wxMpService.getQrcodeService().qrCodePicture(ticket);

        response.setHeader("Location", "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + URLUtil.encode(ticket.getTicket()));
        response.setStatus(HttpStatus.FOUND.value());
    }
}
